package org.example.platform.binding;

import cn.bugstack.mybatis.session.Configuration;
import cn.hutool.core.lang.ClassScanner;
import org.example.platform.session.SqlSeesion;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 映射器注册机
 */
public class MapperRegistry {

    private Configuration config;

    public MapperRegistry(Configuration config) {
        this.config = config;
    }



    // 将已添加的映射器代理加入到hashmap
    private final Map<Class<?>,MapperProxyFactory<?>> knownMappers = new HashMap<>();

    public <T> T getMapper(Class<T> type, SqlSeesion sqlSeesion) throws Exception {
        final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);

        if(mapperProxyFactory == null){
            throw new Exception("type is not find");
        }
        try{
            return mapperProxyFactory.newInstance(sqlSeesion);
        }catch (Exception e){
            throw new Exception(e);
        }
    }

    public <T> void addMapper(Class<T> type) throws Exception {
        // mapper必须是接口才会注册
        if(type.isInterface()){
            if(hasMapper(type)){
                // 重复添加
                throw new Exception("重复添加"+type);
            }
            // 注册映射器代理工厂
            knownMappers.put(type,new MapperProxyFactory<>((Class<Object>) type));
        }
    }

    public <T> boolean hasMapper(Class<T> type) {
        return knownMappers.containsKey(type);
    }

    public void addMappers(String packageName) throws Exception {
        Set<Class<?>> mapperSet =  ClassScanner.scanPackage(packageName);
        for (Class<?> mapperClass : mapperSet) {
            addMapper(mapperClass);
        }
    }


}
